package common.heap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 347. 前 K 个高频元素
 */
public class _347_TopKFrequent {

    public static int[] topKFrequent(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return new int[0];
        }

        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int count = map.getOrDefault(nums[i], 0);
            map.put(nums[i], count + 1);
        }

        ArrayList<Integer>[] array = new ArrayList[nums.length];
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (array[entry.getValue()] == null) {
                array[entry.getValue()] = new ArrayList<>();
            }
            array[entry.getValue()].add(entry.getKey());
        }
        int[] res = new int[k];
        for (int i = array.length - 1, j = 0; i >= 0 && j < k; i--) {
            if (array[i] == null) {
                continue;
            }
            for (int p = 0; p < array[i].size() && j < k; p++) {
                res[j++] = array[i].get(p);
            }
        }
        return res;
    }

    public static void main(String[] args) {


        System.out.println(topKFrequent(new int[]{1, 1, 1, 2, 2, 3}, 2));
    }
}
